import nukescripts
import nuke
from nuke import nodes
def autocrop(first=None, last=None, inc=None, layer="rgba"):

  # Sort out execute range
  root = nuke.root()
  if first is None:
    first = int(root.knob("first_frame").value())
  if last is None:
    last = int(root.knob("last_frame").value())
  if inc is None:
    inc = 1

  # Remember original set of selected nodes...we'll need this
  original_nodes = nuke.selectedNodes()

  # Deselect everything so we can add CurveTool nodes
  all_nodes = nuke.allNodes()
  for i in all_nodes:
    i.knob("selected").setValue(False)

  for i in original_nodes:
    # Reselect originally selected nodes and create a CurveTool node,
    # which will automatically connect to the last selected.
    i.knob("selected").setValue(True)
    autocropper = nuke.createNode("CurveTool",
      '''operation 0 ROI {0 0 input.width input.height} Layer %s label "Processing Crop..." selected true''' % (str(layer), ), False)

    # Execute the CurveTool node thru all the frames
    nuke.executeMultiple([autocropper,], ([first, last, inc],))

    # select the curvewriter
    autocropper.knob("selected").setValue(True)

    # add crop node
    cropnode = nuke.createNode("Crop", "label AutoCrop", False)

    # put the new data from the autocrop into the new crop
    cropbox = cropnode.knob("box");
    autocropbox = autocropper.knob("autocropdata");
    cropbox.copyAnimations(autocropbox.animations())

    # turn on the animated flag
    cropnode.knob("indicators").setValue(1)

    # deselect everything
    all_nodes = nuke.allNodes()
    for j in all_nodes:
      j.knob("selected").setValue(False)

    # select the curvewriter and delete it
    autocropper.knob("selected").setValue(True)

    # delete the autocropper to make it all clean
    nuke.delete(autocropper)

    # deselect everything
    all_nodes = nuke.allNodes()
    for j in all_nodes:
      j.knob("selected").setValue(False)

    # select the new crop
    cropnode.knob("selected").setValue(True)

    # place it in a nice spot
    nuke.autoplace(cropnode)

    # De-Select it
    cropnode.knob("selected").setValue(False)
    return cropnode


def autoFrameAnimated():
    tn = nuke.thisNode()
    tn.begin()

    sn = nuke.toNode('TransformFrame')
    inputNode = nuke.toNode('In').input(0)
    if 'Crop' in inputNode.Class():
        nuke.delete(inputNode)
        inputNode = nuke.toNode('In').input(0)
    inputNode.setSelected(True)
    cropNode = autocrop()
    first_frame = int(nuke.root()['first_frame'].getValue())
    last_frame = int(nuke.root()['last_frame'].getValue())
    margin = tn['margin'].getValue()

    sn['scale'].setValue(0, 0)
    sn['scale'].setValue(0, 1)
    sn['translate'].clearAnimated()
    sn['scale'].clearAnimated()
    sn['translate'].setAnimated(0, True)
    sn['translate'].setAnimated(1, True)
    sn['scale'].setAnimated(0, True)
    sn['scale'].setAnimated(1, True)


    for i in range(first_frame,last_frame+1):
        if i == first_frame or i == last_frame or cropNode['box'].getValueAt(i, 0) != cropNode['box'].getValueAt(i-1, 0) or cropNode['box'].getValueAt(i, 1) != cropNode['box'].getValueAt(i-1, 1) or cropNode['box'].getValueAt(i, 2) != cropNode['box'].getValueAt(i-1, 2) or cropNode['box'].getValueAt(i, 3) != cropNode['box'].getValueAt(i-1, 3):
            sn['translate'].setValueAt((cropNode['box'].getValueAt(i, 0)-margin), i, 0)
            sn['translate'].setValueAt((cropNode['box'].getValueAt(i, 1)-margin), i, 1)
            sn['scale'].setValueAt(((cropNode['box'].getValueAt(i, 2) - cropNode['box'].getValueAt(i, 0))+margin*2)/100, i, 0)
            sn['scale'].setValueAt(((cropNode['box'].getValueAt(i, 3) - cropNode['box'].getValueAt(i, 1))+margin*2)/100, i, 1)

    tn.end()



